package com.css.dzj.dzjap.modules.info.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.css.aq.server.service.BaseService;
import com.css.dzj.dzjap.common.util.BeanUtil;
import com.css.dzj.dzjap.common.util.Constant;
import com.css.dzj.dzjap.common.util.R;
import com.css.dzj.dzjap.modules.apunit.entity.ApUnitEntity;
import com.css.dzj.dzjap.modules.info.service.EvalUnitService;
import com.css.dzj.dzjap.modules.info.vo.EvalInfoVo;
import com.css.dzj.dzjap.modules.todolist.entity.ApTodoEntity;
import com.css.dzj.dzjap.modules.todolist.service.ApTodoService;
import com.querydsl.core.QueryResults;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 安平单位
 *
 * @author liangxingguo
 */
@RestController
@RequestMapping("/evalunit")
@PropertySource(value = "classpath:base.properties")
public class EvalUnitController {

    @Autowired
    EvalUnitService evalUnitService;
    @Autowired
    ApTodoService apTodoService;
    @Value("${SAVE_USER}")
    String SAVE_USER;
    @Value("${BASE_URL}")
    private String BASE_URL;
    @Autowired
    BaseService baseService;

    /**
     * 分页查询评价单位
     *
     * @param pageNo
     * @param pageSize
     * @param unitName 单位名称
     * @param uniscid  统一社会信用代码
     * @param spStatus 审批状态  1:未审批 2：审批不通过3：审批通过
     * @param spPerson 审批人
     * @return
     */
    @GetMapping("/listpage")
    public R getPageEval(@RequestParam Integer pageNo, @RequestParam Integer pageSize,
                         @RequestParam(name = "unitName", required = false) String unitName,
                         @RequestParam(name = "uniscid", required = false) String uniscid,
                         @RequestParam(name = "startTime", required = false) String startTime,
                         @RequestParam(name = "endTime", required = false) String endTime,
                         @RequestParam(name = "spStatus", required = false) String spStatus,
                         @RequestParam(name = "spPerson", required = false) String spPerson,
                         @RequestParam(name = "sbStatus", required = false) String sbStatus,
                         HttpServletRequest request) {
        try {
            PageRequest pageRequest = PageRequest.of(pageNo - 1, pageSize);
            QueryResults page = evalUnitService.getPage(pageRequest, unitName, uniscid, startTime, endTime, spStatus, spPerson, sbStatus, request);
            baseService.logSuccess(3, "查询成功", "2");
            return R.ok().put("page", page);
        } catch (Exception e) {
            baseService.logFailed(3, "查询失败", "2");
            return R.error(e.getMessage());
        }
    }


    /**
     * 分页查询评价单位
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/listeval")
    public R getEval(@RequestParam Integer pageNo, @RequestParam Integer pageSize,
                     @RequestParam(name = "enterpriseName", required = false) String enterpriseName,
                     @RequestParam(name = "enterpriseIdNumber", required = false) String enterpriseIdNumber) {
        PageRequest pageRequest = PageRequest.of(pageNo - 1, pageSize);
        QueryResults page = evalUnitService.getPageEval(pageRequest, enterpriseName, enterpriseIdNumber);
        List<ApUnitEntity> list = page.getResults();
        List<EvalInfoVo> evalInfoVoList = new ArrayList<>();
        for (ApUnitEntity apUnitEntity : list) {
            EvalInfoVo evalInfoVo = new EvalInfoVo();
            evalInfoVo.setEnterpriseName(apUnitEntity.getUnitName());
            evalInfoVo.setEnterpriseIdNumber(apUnitEntity.getUniscid());
            evalInfoVo.setEnterpriseIdType(apUnitEntity.getQyUnitType());
            evalInfoVo.setLegalMan(apUnitEntity.getLegalMan());
            evalInfoVo.setRecordUnitUser(apUnitEntity.getLinkMan());
            evalInfoVo.setRecordUnitPhone(apUnitEntity.getLinkTel());
            evalInfoVoList.add(evalInfoVo);
        }
        QueryResults queryResults = new QueryResults(evalInfoVoList, page.getTotal(), page.getOffset(), page.getTotal());
        baseService.logSuccess(3, "查询成功", "2");
        return R.ok().put("data", queryResults);
    }

    /***
     *逻辑删除评价单位
     * @param id
     * @return
     */
    @PostMapping("/delConstr/{id}")
    public R delEval(@PathVariable String id) {
        boolean flag = evalUnitService.delEval(id);
        if (flag) {
            baseService.logSuccess(3, "删除成功", "2");
            return R.ok("删除成功");
        }
        baseService.logSuccess(3, "删除失败", "2");
        return R.error("删除失败");
    }

    /***
     * 根据Id查找评价单位
     * @param id
     * @return
     */
    @PostMapping("/findbyid/{id}")
    public R findById(@PathVariable String id) {
        if (!StringUtils.isEmpty(id)) {
            ApUnitEntity apUnitEntity = evalUnitService.findById(id);
            baseService.logSuccess(3, "查询成功", "2");
            return R.ok().put("apUnitEntity", apUnitEntity);
        } else {
            baseService.logFailed(3, "查询失败", "2");
            return R.error("Id为空");
        }

    }

    /***
     * 上报评价单位
     * @param apUnitEntity
     * @return
     */
    @PostMapping("/updatebyid/{sbstatus}")
    public R upadateById(@PathVariable String sbstatus, @RequestBody ApUnitEntity apUnitEntity) {
        ApUnitEntity apUnitEntity1 = evalUnitService.findById(apUnitEntity.getId());
        if (!StringUtils.isEmpty(apUnitEntity1)) {
            if ("3".equals(apUnitEntity.getSpStatus())) {
                BeanUtil.copyBeanNotEmptyToBean(apUnitEntity, apUnitEntity1);
                ApTodoEntity apTodoEntity = apTodoService.findByLinkId(apUnitEntity.getId());
                if (!StringUtils.isEmpty(apTodoEntity)) {
                    apTodoEntity.setStatus(apUnitEntity.getSpStatus());
                    apTodoService.update(apTodoEntity);
                }
                apUnitEntity1.setUpdateTime(new Date());
                apUnitEntity1.setSpTime(new Date());
                apUnitEntity1.setSbStatus(sbstatus);
                evalUnitService.update(apUnitEntity1);
                baseService.logSuccess(3, "更新成功", "2");
                return R.ok();
            } else {

                return R.error("审批未通过不能上报");
            }
        } else {
            baseService.logFailed(3, "更新失败", "2");
            return R.error("操作失败");
        }
    }

    /***
     * 审批
     * @param apUnitEntity
     * @return
     */
    @PostMapping("/update")
    public R upadateSp(@RequestBody ApUnitEntity apUnitEntity) {
        Map<String, String> map = new HashMap();
        ApUnitEntity apUnitEntity1 = evalUnitService.findById(apUnitEntity.getId());
        if (!StringUtils.isEmpty(apUnitEntity1)) {
            BeanUtil.copyBeanNotEmptyToBean(apUnitEntity, apUnitEntity1);
            ApTodoEntity apTodoEntity = apTodoService.findByLinkId(apUnitEntity.getId());
            if (!StringUtils.isEmpty(apTodoEntity)) {
                apTodoEntity.setStatus(Constant.STATUSYB);
                apTodoService.update(apTodoEntity);
            }
            if (Constant.CHECK_RESULT_YES.equals(apUnitEntity1.getCheckResult())) {
                String url = BASE_URL + SAVE_USER;
                if (!StringUtils.isEmpty(apUnitEntity.getUserName())) {
                    String loginName = apUnitEntity.getUserName();
                    map.put("loginName", loginName);
                } else {
                    return R.error("用户名不能为空");
                }

                if (!StringUtils.isEmpty(apUnitEntity.getPassword())) {
                    String password = apUnitEntity.getPassword();
                    map.put("password", password);
                } else {
                    return R.error("密码不能为空");
                }
                String anping = "anping";
                /*map.put("userSystem",anping);
                HttpClientUtil.doPost(url,map);*/
                baseService.add(apUnitEntity.getUserName(), anping, apUnitEntity.getPassword());
            }
            if (Constant.CHECK_RESULT_YES.equals(apUnitEntity1.getCheckResult())) {
                apUnitEntity1.setSpStatus(Constant.CHECK_STATUS3);
            }
            if (Constant.CHECK_RESULT_NO.equals(apUnitEntity1.getCheckResult())) {
                apUnitEntity1.setSpStatus(Constant.CHECK_STATUS2);
            }
            apUnitEntity1.setCheckResult(apUnitEntity.getCheckResult());
            apUnitEntity1.setUpdateTime(new Date());
            Date date = new Date();
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            Date date1 = null;
            try {
                date1 = sf.parse(sf.format(date));
                System.out.println(date1);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            apUnitEntity1.setSpTime(date1);
            evalUnitService.update(apUnitEntity1);
            baseService.logSuccess(3, "更新成功", "2");
            return R.ok();
        } else {
            baseService.logFailed(3, "更新失败", "2");
            return R.error("操作失败");
        }
    }

    /***
     * 获取安评单位数量
     * @return
     */
    @GetMapping("/countunit")
    public R countunit() {
        HashMap count = evalUnitService.getCount();
        return R.ok().put("count", count);
    }

    /***
     * 获取安评单位数量根据年度
     * @return
     */
    @GetMapping("/countunityear")
    public R countunitByYear(String year) {
        HashMap count = evalUnitService.getCountByYear(year);
        return R.ok().put("count", count);
    }

    /*********************************************** 门户调用接口 start *********************************************************************/

    /**
     * 门户：分页查询评价单位，不需要判断用户
     *
     * @param pageNo
     * @param pageSize
     * @param unitName
     * @param uniscid
     * @param startTime
     * @param endTime
     * @param spStatus
     * @param spPerson
     * @param sbStatus
     * @return
     */
    @GetMapping("/getPage")
    public QueryResults getEvalPage(@RequestParam Integer pageNo, @RequestParam Integer pageSize,
                                    @RequestParam(name = "unitName", required = false) String unitName,
                                    @RequestParam(name = "uniscid", required = false) String uniscid,
                                    @RequestParam(name = "startTime", required = false) String startTime,
                                    @RequestParam(name = "endTime", required = false) String endTime,
                                    @RequestParam(name = "spStatus", required = false) String spStatus,
                                    @RequestParam(name = "spPerson", required = false) String spPerson,
                                    @RequestParam(name = "sbStatus", required = false) String sbStatus) {
        PageRequest pageRequest = PageRequest.of(pageNo - 1, pageSize);
        QueryResults page = evalUnitService.getPage(pageRequest, unitName, uniscid, startTime, endTime, spStatus, spPerson, sbStatus);
        return page;
    }

    @GetMapping("/getList")
    public List getEvalList(@RequestParam(name = "unitName", required = false) String unitName,
                            @RequestParam(name = "uniscid", required = false) String uniscid,
                            @RequestParam(name = "startTime", required = false) String startTime,
                            @RequestParam(name = "endTime", required = false) String endTime,
                            @RequestParam(name = "spStatus", required = false) String spStatus,
                            @RequestParam(name = "spPerson", required = false) String spPerson,
                            @RequestParam(name = "sbStatus", required = false) String sbStatus) {
        List<ApUnitEntity> list = evalUnitService.queryByParams(unitName, uniscid, startTime, endTime, spStatus, spPerson, sbStatus);
        return list;
    }

    /**
     * 根据ids(逗号分隔)查询List数据
     *
     * @param ids
     * @return
     */
    @GetMapping("/getListByIds")
    public List exportToExcel(@RequestParam String ids) {
        List<ApUnitEntity> list = evalUnitService.queryByIds(ids);
        return list;
    }

    /**
     * 获取总数
     *
     * @return
     */
    @GetMapping("/getTotalCount")
    public Integer getTotalCount() {
        Integer count = evalUnitService.getTotalCount();
        return count;
    }
    /*********************************************** 门户调用接口 end *********************************************************************/

}
